﻿using System;
using System.Collections.Generic;
using System.Text;

namespace MLForgeSharp.Models.SupervisedLearningModels.Linear
{
    /// <summary>
    /// 线性回归模型
    /// </summary>
    public class LinearRegModel
    {
        private double[] weights; // 权重向量
        private double bias; // 偏置项
        private double learningRate; // 学习率
        private int maxIterations; // 最大迭代次数

        public LinearRegModel(double learningRate = 0.01, int maxIterations = 1000)
        {
            this.learningRate = learningRate;
            this.maxIterations = maxIterations;
        }

        // 训练模型
        public void Train(double[][] data, double[] targets)
        {
            int numSamples = data.Length;
            int numFeatures = data[0].Length;
            weights = new double[numFeatures];
            bias = 0.0;

            for (int iter = 0; iter < maxIterations; iter++)
            {
                double[] gradientsWeights = new double[numFeatures];
                double gradientBias = 0.0;

                for (int i = 0; i < numSamples; i++)
                {
                    double prediction = Predict(data[i]);
                    double error = prediction - targets[i];

                    for (int j = 0; j < numFeatures; j++)
                    {
                        gradientsWeights[j] += error * data[i][j];
                    }
                    gradientBias += error;
                }

                for (int j = 0; j < numFeatures; j++)
                {
                    weights[j] -= learningRate * gradientsWeights[j] / numSamples;
                }
                bias -= learningRate * gradientBias / numSamples;
            }
        }

        // 预测
        public double Predict(double[] features)
        {
            double prediction = bias;
            for (int i = 0; i < features.Length; i++)
            {
                prediction += weights[i] * features[i];
            }
            return prediction;
        }
    }

    // 示例程序
    public class LinearRegModelExample
    {
        public LinearRegModelExample()
        {
            // 示例数据
            double[][] data = new double[][]
        {
            new double[] { 1.0 },
            new double[] { 2.0 },
            new double[] { 3.0 },
            new double[] { 4.0 },
            new double[] { 5.0 }
        };

            double[] targets = { 1.0, 2.0, 3.0, 4.0, 5.0 }; // 目标值

            // 创建模型
            LinearRegModel model = new LinearRegModel(learningRate: 0.01, maxIterations: 1000);

            // 训练模型
            model.Train(data, targets);

            // 预测
            double[] testFeatures = { 6.0 };
            double predictedValue = model.Predict(testFeatures);

            System.Console.WriteLine("预测值: " + predictedValue);
        }
    }
}
